<template>
    <div>
        <el-row type="flex" justify="end" class="header toolbar">
            <el-col :span="2" class="header-btn">
                <el-button type="primary" @click="addUser">添加</el-button>
            </el-col>
        </el-row>
        <!-- 表格开始  -->
        <el-table
                stripe
                ref="multipleTable"
                :data="userList"
                tooltip-effect="dark"
                style="width: 100%">
            <el-table-column
                    type="selection"
                    width="55">
            </el-table-column>
            <el-table-column
                    label="用户名">
                <template slot-scope="scope">{{ scope.row.username }}</template>
            </el-table-column>
            <el-table-column
                    prop="merch_name"
                    label="商户">
            </el-table-column>
            <el-table-column
                    prop="store_name"
                    label="门店">
            </el-table-column>
            <el-table-column
                    prop="status"
                    label="状态">
                <template slot-scope="scope">{{ scope.row.status ? '启用': '禁用' }}</template>
            </el-table-column>
            <el-table-column
                    prop="create_time"
                    label="添加时间">
            </el-table-column>
            <el-table-column
                    label="操作"
                    width="250">
                <template slot-scope="scope">
                    <el-button type="info" size="mini" @click="editUser(scope.$index, scope.row, 'edit')">编辑</el-button>
                    <el-button type="danger" size="mini" @click="delUser(scope.$index, scope.row)">删除</el-button>
                    <el-button type="primary" size="mini" @click="assignRoles(scope.$index, scope.row)">分配角色</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 页码 -->
        <el-col :span="24" class="toolbar">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="pageSizes"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </el-col>

        <!--   添加用户dialog     -->
        <el-dialog
                title="添加用户"
                :visible.sync="addDialogVisible"
                width="50%"
                @close="addClose">
            <el-form :model="addRuleForm" :rules="rules" ref="addRuleForm" label-width="100px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addRuleForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addRuleForm.password" type="password"></el-input>
                </el-form-item>
                <el-form-item label="商户">
                    <el-select v-model="addRuleForm.merch_id" placeholder="选择商户" @change="changeMerch">
                        <el-option
                                v-for="item in merchs"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="门店">
                    <el-select v-model="addRuleForm.store_id" placeholder="选择门店" @change="changeStores">
                        <el-option
                                v-for="item in stores"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="状态">
                    <el-switch
                            v-model="addRuleForm.status"
                            inactive-text="禁用"
                            active-text="启用"
                            :active-value="1"
                            :inactive-value="0">
                    </el-switch>
                </el-form-item>
            </el-form>
            <span slot="footer">
                <el-button @click="addClose">取 消</el-button>
                <el-button type="primary" @click="addSure">确 定</el-button>
            </span>
        </el-dialog>

        <!--   编辑用户dialog     -->
        <el-dialog
                title="编辑用户"
                :visible.sync="editDialogVisible"
                width="50%"
                @close="editClose">
            <el-form :model="editRuleForm" :rules="rules" ref="editRuleForm" label-width="100px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="editRuleForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码">
                    <el-input v-model="editRuleForm.password" type="password"></el-input>
                </el-form-item>
                <el-form-item label="商户">
                    <el-select v-model="editRuleForm.merch_id" placeholder="选择商户" @change="editChangeMerch">
                        <el-option
                                v-for="item in merchs"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="门店">
                    <el-select v-model="editRuleForm.store_id" placeholder="选择门店" @change="editChangeStores">
                        <el-option
                                v-for="item in stores"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="状态">
                    <el-switch
                            v-model="editRuleForm.status"
                            inactive-text="禁用"
                            active-text="启用"
                            :active-value="1"
                            :inactive-value="0">
                    </el-switch>
                </el-form-item>
            </el-form>
            <span slot="footer">
                <el-button @click="editClose">取 消</el-button>
                <el-button type="primary" @click="editSure">确 定</el-button>
            </span>
        </el-dialog>

        <!--   分配角色dialog    -->
        <el-dialog
                title="分配角色"
                :visible.sync="distributeDialogVisible"
                width="50%"
                @close="distributeClose">
            <el-form ref="distributeRuleForm" label-width="100px">
                <el-form-item label="角色">
                    <el-checkbox-group v-model="checkList" @change="checkboxChange">
                        <el-checkbox :label="item.id" v-for="item in authList" :key="item.id">{{ item.name }}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
            <span slot="footer">
                <el-button @click="distributeClose">取 消</el-button>
                <el-button type="primary" @click="distributeSure">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import { getUser, addUser, editUserInfo, delUserInfo, getGroupByUid, setGroupByUid, authGroupList } from '../../api/userAPI'
    import { merchkList, storeList } from '../../api/merchAPI'
    export default {
        name: "User",
        data() {
            return {
                tableData: [],
                // status: '',
                // keyword: '',
                userList: [],
                total: 0,
                pageSize: 10, // 每页显示条目个数
                pageSizes: [10, 20, 30, 40], // 每页显示个数选择器的选项设置
                currentPage: 1, // 当前页数
                addDialogVisible: false,
                addRuleForm: {
                    username: '',
                    password: '',
                    merch_id: '',
                    store_id: '',
                    status: 1
                },
                rules: {
                    username: [
                        { required: true, message: '请输入用户名', trigger: 'blur' },
                    ],
                    password: [
                        { required: true, message: '请输入密码', trigger: 'blur' },
                    ]
                },
                merchs: [],
                stores: [],
                editRuleForm: {},
                editRuleFormCopy: {},
                editDialogVisible: false,
                distributeDialogVisible: false,
                checkList: [],
                authList: [],
                groupByBidList: [],
                currentUser: {}
            }
        },
        created() {
            this._getUser() // 获取后台用户列表
        },
        methods: {
            _getUser() {
                let data = {p: this.currentPage, length: this.pageSize}
                getUser(data).then(res => {
                    this.userList = res.data.user
                    this.total = res.data.total
                }).catch(err => {
                    this.$message.error(err.response.data.message)
                })
            },
            editUser(index, row, data) {
                console.log(row)
                // console.log(data)
                this.editDialogVisible = true
                this.editRuleForm = row
                this.editRuleFormCopy = { ...this.editRuleForm }
                this._merchkList(data)
            },
            delUser(index, row) {
                console.log(row)
                this.$confirm('确认删除该用户吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    let data = {ids: [row.id],delete: 1}
                    delUserInfo(data).then(res => {
                        this.$message.success('删除成功')
                        this._getUser() // 获取后台用户列表
                    }).catch(err => {
                        this.$message.error(err.response.data.message)
                    })
                }).catch(() => {
                    this.$message.info('已取消')
                })
            },
            handleSizeChange(val) {
                console.log(`每页 ${val} 条`)
                // 改变每页显示的条数
                this.pageSize = val
                this.currentPage = 1 // 注意：在改变每页显示的条数时，要将页码显示到第一页
                this._getUser() // 获取后台用户列表

            },
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`)
                this.currentPage = val
                // this.currentPage = 1
                this._getUser() // 获取后台用户列表
            },
            addUser() {
                this.addDialogVisible = true
                this._merchkList()
            },
            addClose() {
                this.$refs.addRuleForm.resetFields()
                this.addDialogVisible = false
                this.addRuleForm.merch_id = ''
                this.addRuleForm.store_id = ''
                this.addRuleForm.status = 1
            },
            _merchkList(data) {
                // const res = await merchkList()
                // this.merchs = res.data.merch
                merchkList().then(res => {
                    this.merchs = res.data.merch
                }).catch(err => {
                    this.$message.error(err.response.data.message)
                })
                if (data) {
                    // console.log(data)
                    this._storeList(this.editRuleForm.merch_id)
                }
            },
            changeMerch(val) {
                console.log(val)
                this.addRuleForm.merch_id = val
                this.addRuleForm.store_id = ''
                this._storeList(val)
            },
            _storeList(merchId) {
                // const res = await storeList()
                // console.log(res)
                let data = {merch_id: merchId}
                storeList(data).then(res => {
                    this.stores = res.data.store
                }).catch(err => {
                    this.$message.error(err.response.data.message)
                })
            },
            changeStores(val) {
                console.log(val)
                this.addRuleForm.store_id = val
            },
            addSure() {
                this.$refs.addRuleForm.validate( (valid) => {
                    if (!valid) return false
                    console.log(this.addRuleForm)
                    // const res = await addUser(this.addRuleForm)
                    addUser(this.addRuleForm).then(res => {
                        this.$message.success('添加成功')
                        this.addDialogVisible = false
                        this._getUser() // 获取后台用户列表
                    }).catch(err => {
                        this.$message.error(err.response.data.message)
                    })
                })
            },
            editClose() {
                this.$refs.editRuleForm.resetFields()
                this.editDialogVisible = false
                this.editRuleForm.password = ''
                this.editRuleForm.merch_id = this.editRuleFormCopy.merch_id
                this.editRuleForm.store_id = this.editRuleFormCopy.store_id
                this.editRuleForm.status = this.editRuleFormCopy.status
            },
            editChangeMerch(val) {
                console.log(val)
                this.editRuleForm.merch_id = val
                this.editRuleForm.store_id = ''
                this._storeList(val)
            },
            editChangeStores(val) {
                console.log(val)
                this.editRuleForm.store_id = val
            },
            editSure() {
                this.$refs.editRuleForm.validate( async (valid) => {
                    if (!valid) return false
                    // console.log(this.editRuleForm)
                    let data = {
                        id: this.editRuleForm.id,
                        username: this.editRuleForm.username,
                        password: this.editRuleForm.password ? this.editRuleForm.password : '',
                        merch_id: this.editRuleForm.merch_id,
                        store_id: this.editRuleForm.store_id,
                        status: this.editRuleForm.status,
                    }
                    if (!data.password) {
                        delete data.password
                    }
                    if (!data.merch_id) {
                        delete data.merch_id
                    }
                    if (!data.store_id) {
                        delete data.store_id
                    }
                    // console.log(data)
                    editUserInfo(data).then(res => {
                        this.$message.success('修改成功')
                        this.editDialogVisible = false
                        this._getUser() // 获取后台用户列表
                    }).catch(err => {
                        this.$message.error(err.response.data.message)
                    })
                })
            },
            assignRoles(index, row) {
                console.log(row)
                this.currentUser = row
                this.distributeDialogVisible = true
                this._authGroupList(row.id)
            },
            _authGroupList(id) {
                authGroupList().then(res => {
                    console.log(res)
                    this.authList = res.data.list
                    getGroupByUid({uid: id}).then(res => {
                        console.log(res)
                        this.groupByBidList = res.data.list
                        this.checkList = this.groupByBidList.map(item => item.group_id)
                        console.log(this.checkList)
                    }).catch(err => {
                        this.$message.error(err.response.data.message)
                    })
                    // this.total = res.data.total
                }).catch(err => {
                    this.$message.error(err.response.data.message)
                })
            },
            distributeClose() {
                this.distributeDialogVisible = false
            },
            distributeSure() {
                console.log(this.currentUser)
                let data = {uid: this.currentUser.id, groupId: this.checkList}
                setGroupByUid(data).then(res => {
                    console.log(res)
                    this.distributeDialogVisible = false
                    this.$message.success('修改成功')
                    this._getUser() // 获取后台用户列表
                }).catch(err => {
                    this.$message.error(err.response.data.message)
                })
            },
            checkboxChange(val) {
                console.log(val)
                this.checkList = val
            }
        }
    }
</script>

<style scoped lang="scss">
    .header {
        /*margin-top: 10px;*/
    }
    .el-input,.el-select {
        width: 80%;
    }
</style>
